import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/dynamic_model.dart';

/// 个人页面视图模型
class PersonalNavigatorViewModel extends BaseViewModel {
  PersonalNavigatorViewModel() {
    // 监听 userStore 的变化
    appState.userStore.addListener(_onUserStoreChanged);
    // 监听 contentBroadcaster 的变化（用于实时更新点赞数）
    appState.contentBroadcaster.addListener(_onContentChanged);
    // 监听 followManager 的变化（用于实时更新粉丝/关注数）
    appState.followManager.addListener(_onFollowChanged);
  }

  void _onUserStoreChanged() {
    notifyListeners();
  }

  void _onContentChanged() {
    notifyListeners();
  }

  void _onFollowChanged() {
    notifyListeners();
  }

  @override
  void dispose() {
    appState.userStore.removeListener(_onUserStoreChanged);
    appState.contentBroadcaster.removeListener(_onContentChanged);
    appState.followManager.removeListener(_onFollowChanged);
    super.dispose();
  }

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 获取用户发布的动态列表
  List<ContentModel> get userDynamics {
    if (!isLoggedIn || currentUser == null) return [];
    return appState.contentBroadcaster.fetchUserContent(currentUser!.id);
  }

  /// 获取用户统计数据
  Map<String, int> get userStats {
    if (!isLoggedIn || currentUser == null) {
      return {'fan': 0, 'follow': 0, 'like': 0};
    }

    return {
      'fan': appState.followManager.getFollowersCount(currentUser!.id),
      'follow': appState.followManager.getFollowingCount(currentUser!.id),
      'like': appState.contentBroadcaster.getUserTotalLikes(currentUser!.id),
    };
  }

  /// 删除动态
  Future<bool> deleteDynamic(String dynamicId) async {
    if (!isLoggedIn) return false;
    return await appState.contentBroadcaster.removeContent(dynamicId);
  }

  /// 初始化数据
  void initializeData() {
    notifyListeners();
  }
}

/// 个人页面
class PersonalStory extends StatefulWidget {
  const PersonalStory({super.key});

  @override
  State<PersonalStory> createState() => _PersonalStoryState();
}

class _PersonalStoryState extends State<PersonalStory> {
  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<PersonalNavigatorViewModel>.reactive(
      viewModelBuilder: () => PersonalNavigatorViewModel(),
      disposeViewModel: false, // 不自动销毁ViewModel
      initialiseSpecialViewModelsOnce: true, // 只初始化一次ViewModel
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.background),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child:
                  viewModel.isLoggedIn
                      ? _buildLoggedInContent(viewModel)
                      : _buildLoginPrompt(),
            ),
          ),
        );
      },
    );
  }

  /// 构建已登录内容
  Widget _buildLoggedInContent(PersonalNavigatorViewModel viewModel) {
    return Column(
      children: [
        // 标题栏
        _buildTitleBar(),

        // 可滚动内容区域
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                // 用户信息区域
                _buildUserProfileSection(viewModel),

                SizedBox(height: 8.h),

                // 分隔线
                _buildSeparator(),

                SizedBox(height: 8.h),

                // 动态列表
                _buildDynamicsList(viewModel),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建标题栏
  Widget _buildTitleBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          // 标题
          Expanded(
            child: Center(
              child: Text('PERSONAL').blackHanSans(
                fontSize: 24.sp,
                color: MagmaColor.white,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),

          // 设置按钮
          MagmaTap(
            onTap: () {
              QR.to(MagmaRouter.configurationPath);
            },
            child: Image.asset(
              MagmaConstant.setting,
              width: 24.w,
              height: 24.w,
              color: MagmaColor.white,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建用户信息区域
  Widget _buildUserProfileSection(PersonalNavigatorViewModel viewModel) {
    final user = viewModel.currentUser!;
    final stats = viewModel.userStats;

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        children: [
          // 用户头像
          CircleAvatar(radius: 43.r, backgroundImage: AssetImage(user.avatar)),

          SizedBox(height: 6.h),

          // 用户名
          Text(user.username).blackHanSans(
            fontSize: 18.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w700,
          ),

          SizedBox(height: 12.h),

          // 用户简介
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(
                child: Text(
                  'Life Is Not About Waiting For The Storm To Pass, It\'s About Learning To Dance In The Rain.',
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ).inter(
                  fontSize: 12.sp,
                  color: MagmaColor.white.withValues(alpha: 0.8),
                  fontWeight: FontWeight.w400,
                ),
              ),
              SizedBox(width: 6.w),
              MagmaTap(
                onTap: () {
                  QR.to(MagmaRouter.profileEditPath);
                },
                child: Image.asset(
                  MagmaConstant.edit,
                  width: 16.w,
                  height: 16.w,
                  color: MagmaColor.white,
                ),
              ),
            ],
          ),

          SizedBox(height: 24.h),

          // 统计数据
          _buildStatsRow(stats),
        ],
      ),
    );
  }

  /// 构建统计数据行
  Widget _buildStatsRow(Map<String, int> stats) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        _buildStatItem('Fan', stats['fan']!.toString()),
        _buildStatDivider(),
        _buildStatItem('Follow', stats['follow']!.toString()),
        _buildStatDivider(),
        _buildStatItem('Like', stats['like']!.toString()),
      ],
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(value).blackHanSans(
          fontSize: 16.sp,
          color: MagmaColor.purple,
          fontWeight: FontWeight.w700,
        ),
        SizedBox(height: 4.h),
        Text(label).inter(
          fontSize: 13.sp,
          color: MagmaColor.white,
          fontWeight: FontWeight.w400,
        ),
      ],
    );
  }

  /// 构建统计分隔线
  Widget _buildStatDivider() {
    return Container(
      width: 1.w,
      height: 40.h,
      color: MagmaColor.white.withOpacity(0.3),
    );
  }

  /// 构建分隔线
  Widget _buildSeparator() {
    return Image.asset(
      MagmaConstant.decoration,
      width: double.infinity,
      fit: BoxFit.fitWidth,
    );
  }

  /// 构建动态列表
  Widget _buildDynamicsList(PersonalNavigatorViewModel viewModel) {
    final dynamics = viewModel.userDynamics;

    if (dynamics.isEmpty) {
      return Center(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 40.h),
          child: Text(
            'No posts yet',
          ).inter(fontSize: 16.sp, color: MagmaColor.white.withOpacity(0.6)),
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        children:
            dynamics.map((dynamic) {
              return _buildDynamicItem(dynamic, viewModel);
            }).toList(),
      ),
    );
  }

  /// 构建动态项
  Widget _buildDynamicItem(
    ContentModel dynamic,
    PersonalNavigatorViewModel viewModel,
  ) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: MagmaTap(
        onTap: () {
          QR.to(
            MagmaRouter.dynamicDetailPath.replaceAll(':dynamicId', dynamic.id),
          );
        },
        child: Container(
          decoration: BoxDecoration(
            color: MagmaColor.black,
            borderRadius: BorderRadius.circular(6.r),
            border: Border.all(color: MagmaColor.white, width: 1.w),
          ),
          child: Padding(
            padding: EdgeInsets.all(16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 发布日期和删除按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'Release Date: ${_formatDate(dynamic.createdAt)}',
                    ).blackHanSans(
                      fontSize: 14.sp,
                      color: MagmaColor.white,
                      fontWeight: FontWeight.w400,
                    ),
                    MagmaTap(
                      onTap: () => _showDeleteDialog(dynamic, viewModel),
                      child: Image.asset(
                        MagmaConstant.delete,
                        width: 20.w,
                        height: 20.w,
                        color: MagmaColor.white,
                      ),
                    ),
                  ],
                ),

                SizedBox(height: 12.h),

                // 动态图片
                AspectRatio(
                  aspectRatio: 346 / 232,
                  child: Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2.r),
                      image: DecorationImage(
                        image: AssetImage(
                          dynamic.imagePath ??
                              dynamic.coverImagePath ??
                              MagmaConstant.dynamic1,
                        ),
                        fit: BoxFit.cover,
                      ),
                    ),
                    child:
                        dynamic.type == ContentType.video
                            ? Center(
                              child: Icon(
                                Icons.play_arrow,
                                color: Colors.white,
                                size: 48.w,
                              ),
                            )
                            : null,
                  ),
                ),

                SizedBox(height: 12.h),

                // 动态详情文字（两行）
                Text(
                  dynamic.content,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ).inter(
                  fontSize: 16.sp,
                  color: MagmaColor.white,
                  fontWeight: FontWeight.w400,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建登录提示
  Widget _buildLoginPrompt() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Logo
          ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: Image.asset(MagmaConstant.logo, width: 120.w, height: 120.w),
          ),

          SizedBox(height: 32.h),

          // 提示文字
          Text(
            'Please login to view your profile',
            textAlign: TextAlign.center,
          ).inter(
            fontSize: 18.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w600,
          ),

          SizedBox(height: 16.h),

          Text(
            'Manage your posts and connect with others',
            textAlign: TextAlign.center,
          ).inter(
            fontSize: 14.sp,
            color: MagmaColor.white.withOpacity(0.7),
            fontWeight: FontWeight.w400,
          ),

          SizedBox(height: 40.h),

          // 登录按钮
          MagmaTap(
            onTap: () => QR.to(MagmaRouter.loginPath),
            child: Container(
              width: 200.w,
              height: 56.h,
              decoration: BoxDecoration(
                color: MagmaColor.purple,
                borderRadius: BorderRadius.circular(28.r),
              ),
              child: Center(
                child: Text('Login').blackHanSans(
                  fontSize: 20.sp,
                  color: MagmaColor.black,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示删除确认对话框
  void _showDeleteDialog(
    ContentModel dynamic,
    PersonalNavigatorViewModel viewModel,
  ) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: MagmaColor.black,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
            side: BorderSide(color: MagmaColor.white, width: 1.w),
          ),
          title: Text('Delete Post').blackHanSans(
            fontSize: 18.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w600,
          ),
          content: Text(
            'Are you sure you want to delete this post? This action cannot be undone.',
          ).inter(
            fontSize: 14.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w400,
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('Cancel').inter(
                fontSize: 14.sp,
                color: MagmaColor.white.withOpacity(0.7),
                fontWeight: FontWeight.w400,
              ),
            ),
            TextButton(
              onPressed: () async {
                Navigator.of(context).pop();
                final result = await viewModel.deleteDynamic(dynamic.id);
                if (result) {
                  viewModel.notifyListeners();
                  MagmaToast.success(
                    context,
                    title: 'Post deleted successfully',
                  );
                } else {
                  MagmaToast.error(context, title: 'Failed to delete post');
                }
              },
              child: Text('Delete').inter(
                fontSize: 14.sp,
                color: MagmaColor.red,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        );
      },
    );
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    const months = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
    ];
    return '${months[date.month - 1]} ${date.day}, ${date.year}';
  }
}
